package com.scs.application.modules.msg.service.impl;

import com.scs.application.core.msg.domain.SceneMessage;
import com.scs.application.core.msg.enums.MessageType;
import com.scs.application.core.msg.enums.ReceiverType;
import com.scs.application.core.msg.provider.SceneMsgPushProvider;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.msg.entity.MessageSend;
import com.scs.application.modules.msg.service.MessageSendService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发送消息 service 实现
 *
 */

@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class MessageSendServiceImpl implements MessageSendService {

    SceneMsgPushProvider sceneMsgPushProvider;

    /**
     * 发送消息
     *
     * @param message
     */
    @Override
    public boolean sendMessage(MessageSend message) {
        if (message.getSendType().equalsIgnoreCase(ReceiverType.USER.name())
                && StringUtils.isBlank(message.getUserIds())){
            return false;
        }
        if (message.getSendType().equalsIgnoreCase(ReceiverType.OFFICE.name())
                && StringUtils.isBlank(message.getOfficeIds())){
            return false;
        }
        SceneMessage sm = new SceneMessage();

        if (ReceiverType.ALL.name().equalsIgnoreCase(message.getSendType())) {
            sm.setReceiver("").setReceiverType(ReceiverType.ALL);
        } else if (ReceiverType.USER.name().equalsIgnoreCase(message.getSendType())) {
            sm.setReceiver(message.getUserIds()).setReceiverType(ReceiverType.USER);
        } else if (ReceiverType.OFFICE.name().equalsIgnoreCase(message.getSendType())) {
            sm.setReceiver(message.getOfficeIds()).setReceiverType(ReceiverType.OFFICE);
        }
        sm.setSceneCode(message.getSceneCode());
        //设置发布人
        sm.addParam("creator", UserUtils.currentUser().getId(), MessageType.INNER);
        //发送消息
        sceneMsgPushProvider.push(sm);
        return true;
    }


}
